﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using web.core.ViewModels;
using web.core.Models;
using web.component;
using System.Configuration;

namespace web.core.Controllers
{
    public class memberController : baseController
    {
        public ActionResult member_login()
        {
            return PartialView("../member/member_login");
        }

        [ChildActionOnly]
        [HttpGet]
        public ActionResult login()
        {
            var old_url = Request.UrlReferrer;
            if (Session["member_id"] != null)
            {
                if (old_url!=null && old_url.ToString() != string.Empty)
                {
                    ViewBag.redirect = old_url;
                }
                else {
                    ViewBag.redirect = "/tai_khoan_ca_nhan.ub";
                }
                
                ViewBag.login = true;
                return PartialView("../Shared/control_redirect");
            }
            else
            {
                return PartialView("../Shared/member/login");
            }
        }

        [ChildActionOnly]
        [HttpPost]
        public ActionResult login(FormCollection values)
        {
            cryptography_component cryCom = new cryptography_component();
            string olUrl = Request.UrlReferrer.AbsoluteUri;
            string redirectStr = "";
            int user_id = 0;
            var login = new ViewModels.LoginViewModels();
            TryUpdateModel(login);

            if ((login.email == null && login.password == null) || login.email == null || login.password == null)
            {
                ViewBag.login = false;
                return PartialView("../Shared/member/login", login);
            }

            try
            {
                string _password = cryCom.MD5(login.password);
                string _salt = _password.Substring(0, 5);
                string _cryptography_password = System.Configuration.ConfigurationManager.AppSettings["CryptographyPassword"].ToString();
                string _initial_vector = System.Configuration.ConfigurationManager.AppSettings["InitialVector"].ToString();
                string pass = cryCom.Encrypt(_password, _cryptography_password, _salt, _initial_vector);
                var user = accountModels.authenticateUserEmail(login.email, pass);
                if (user != null)
                {
                    user_id = user.user_id;
                }

                if (user_id > 0)
                {
                    Session["member_id"] = user_id;

                    if (login.remember)
                    {
                        HttpCookie ck = new HttpCookie("Sercurity_User");
                        ck.Values["username"] = login.username;
                        ck.Values["password"] = login.password;
                        ck.Values["user_id"] = user_id.ToString();
                        ck.Values["remember"] = login.remember.ToString();
                        ck.Expires = DateTime.Now.AddDays(1);//Thoi han luu cookie
                        HttpContext.Response.Cookies.Add(ck);
                    }


                    //Ghi lại log SignIn

                    if (Session["next_action"] != null)
                    {
                        redirectStr = Session["next_action"].ToString();
                    }
                    else
                    {
                        if (olUrl != string.Empty)
                        {
                            if (olUrl.Contains("dang_nhap.ub"))
                            {
                                redirectStr = "/tai_khoan_ca_nhan.ub"; 
                            }
                            else
                                redirectStr = olUrl;
                        }

                    }
                }
                else
                {
                    Session["member_id"] = null;
                    ViewBag.login = false;
                    ViewBag.error = "Email hoặc mật khẩu của quý khách không chính xác. Xin vui lòng thử lại.";
                    return PartialView("../Shared/member/login", login);
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex);
                Session["member_id"] = null;
                ViewBag.login = false;
                return PartialView("../Shared/member/login", login);
            }
            ViewBag.redirect = redirectStr;
            ViewBag.login = true;
            return PartialView("../Shared/control_redirect");
        }

        public ActionResult logout()
        {
            Session["member_id"] = null;
            return RedirectToAction("member_login", "member");
        }

        public ActionResult member_management()
        {
            IsMember();
            return PartialView("../member/member_management");
        }

        public ActionResult member_change_password()
        {
            IsMember();
            return PartialView("../member/member_change_password");
        }

        [ChildActionOnly]
        [HttpGet]
        public ActionResult control_change_password()
        {
            var change = new ViewModels.ChangePasswordViewModels();
            if (Session["member_id"] != null)
            {
                var user = accountModels.getUserByID(int.Parse(Session["member_id"].ToString()));
                if (user != null)
                {
                    var cus = checkoutModels.GetCustomerByUserID(user.user_id);
                    if (cus != null)
                    {
                        change.full_name = cus.full_name;
                    }
                }
            }
            return PartialView("../Shared/member/change_password",change);
        }

        [ChildActionOnly]
        [HttpPost]
        public ActionResult control_change_password(FormCollection values)
        {
            cryptography_component cryCom = new cryptography_component();
            var change = new ViewModels.ChangePasswordViewModels();
            TryUpdateModel(change);

            if (change.password == null)
            {
                ViewBag.result_message = "Xin vui lòng nhập mật khẩu.";
                ViewBag.result = false;
                return PartialView("../Shared/member/change_password");
            }

            if (change.new_password == null)
            {
                ViewBag.result_message = "Xin vui lòng nhập mật khẩu mới.";
                ViewBag.result = false;
                return PartialView("../Shared/member/change_password");
            }

            if (change.confirm_password == null)
            {
                ViewBag.result_message = "Xin vui lòng xác nhận mật khẩu.";
                ViewBag.result = false;
                return PartialView("../Shared/member/change_password");
            }

            try
            {
                string _password = cryCom.MD5(change.password);
                string _salt = _password.Substring(0, 5);
                string _cryptography_password = System.Configuration.ConfigurationManager.AppSettings["CryptographyPassword"].ToString();
                string _initial_vector = System.Configuration.ConfigurationManager.AppSettings["InitialVector"].ToString();
                string pass = cryCom.Encrypt(_password, _cryptography_password, _salt, _initial_vector);
                if (accountModels.getUserByID(int.Parse(Session["member_id"].ToString())).password.Equals(pass))
                {
                    if (change.new_password.Equals(change.confirm_password))
                    {
                        var user = accountModels.getUserByID(int.Parse(Session["member_id"].ToString()));
                        user.password = cryCom.Encrypt(cryCom.MD5(change.new_password), _cryptography_password, cryCom.MD5(change.new_password).Substring(0, 5), _initial_vector);
                        user.salt = cryCom.MD5(change.new_password).Substring(0, 5);
                        accountModels.changePassword(user);
                    }
                    else
                    {
                        ViewBag.result_message = "Xin vui lòng xác nhận lại mật khẩu.";
                        ViewBag.result = false;
                    }
                }
                else
                {
                    ViewBag.result_message = "Mật khẩu của quý khách không đúng.";
                    ViewBag.result = false;
                }
            }
            catch (Exception ex)
            {
                ViewBag.result_message = "" + ex.Message;
                ViewBag.result = false;
                return PartialView("../Shared/member/change_password");
            }
            ViewBag.result_message = "Thay đổi mật khẩu thành công.";
            ViewBag.result = true;
            ViewBag.redirect = "/tai_khoan_ca_nhan.ub";
            return PartialView("../Shared/control_redirect");
        }

        public ActionResult member_register()
        {
            return PartialView("../member/member_register");
        }

        [ChildActionOnly]
        [HttpGet]
        public ActionResult register()
        {
            var old_url = Request.UrlReferrer;
            if (Session["member_id"] != null)
            {
                if (old_url != null && old_url.ToString() != string.Empty)
                {
                    ViewBag.redirect = old_url;
                }
                else
                {
                    ViewBag.redirect = "/tai_khoan_ca_nhan.ub";
                }

                ViewBag.login = true;
                return PartialView("../Shared/control_redirect");
            }
            else
            {
                var user_view = new ViewModels.MemberViewModels();
                user_view.user_status = 1;
                return PartialView("../Shared/member/register");
            }
            
        }

        [ChildActionOnly]
        [HttpPost]
        public ActionResult register(FormCollection values)
        {
            var user_view = new ViewModels.MemberViewModels();
            TryUpdateModel(user_view);

            //valid form in server code
            if (string.IsNullOrEmpty(user_view.full_name)) {
                ViewBag.result_message = "Quý khách vui lòng điền Họ và Tên.";
                ViewBag.result = false;
                return PartialView("../Shared/member/register", user_view);
            }

            if (string.IsNullOrEmpty(user_view.password) || string.IsNullOrEmpty(user_view.confirm_password) || user_view.confirm_password != user_view.password) {
                ViewBag.result_message = "Quý khách vui lòng nhập mật khẩu và xác nhận mật khẩu.";
                ViewBag.result = false;
                return PartialView("../Shared/member/register", user_view);
            }

            if (string.IsNullOrEmpty(user_view.email)) {
                ViewBag.result_message = "Quý khách vui lòng nhập email.";
                ViewBag.result = false;
                return PartialView("../Shared/member/register", user_view);
            }

            if (string.IsNullOrEmpty(user_view.mobile))
            {
                ViewBag.result_message = "Quý khách vui lòng nhập số điện thoại có giá trị.";
                ViewBag.result = false;
                return PartialView("../Shared/member/register", user_view);
            }

            //check captcha text
            if (HttpContext.Session["captchastring"] != null && user_view.captcha_text != HttpContext.Session["captchastring"].ToString())
            {
                ViewBag.result_message = "Quý khách vui lòng nhập lại mã xác nhận.";
                ViewBag.result = false;
                return PartialView("../Shared/member/register", user_view);
            }

            if (!string.IsNullOrEmpty(user_view.email) && !accountModels.CheckEmailExists(user_view.email))
            {
                ViewBag.result_message = "Email này đã được sử dụng.";
                ViewBag.result = false;
                return PartialView("../Shared/member/register", user_view);
            }

            cryptography_component cryCom = new cryptography_component();
            string _password = cryCom.MD5(user_view.password);
            string _salt = _password.Substring(0, 5);
            string _cryptography_password = System.Configuration.ConfigurationManager.AppSettings["CryptographyPassword"].ToString();
            string _initial_vector = System.Configuration.ConfigurationManager.AppSettings["InitialVector"].ToString();
            string pass = cryCom.Encrypt(_password, _cryptography_password, _salt, _initial_vector);

            web.data.entities.users user = new data.entities.users();
            //user.username = user_view.username;
            user.user_status = 1;
            user.email = user_view.email;
            user.created_date = Udate_time.GetCurrentDateTime();
            user.password = pass;
            user.salt = _salt;
            user.activation_code = null;
            user.active_date = Udate_time.GetCurrentDateTime();

            int new_id = accountModels.createUser(user);

            if (new_id > 0)
            {
                //add group for user
                accountModels.addGroupForUser(2, new_id);           //2 is customer group

                //add new customer
                web.data.entities.customer cus = new data.entities.customer() {
                    full_name = user_view.full_name,
                    mobile = user_view.mobile,
                    email = user_view.email,
                    created_date = DateTime.Now,
                    address = user_view.address,
                    status = true,
                    user_id = new_id
                };
                accountModels.createCustomer(cus);

                //gui email to client
                var mail_id = global_const.EMAIL_ID_NEW_ACCOUNT;
                var lst_content = new List<EmailVariable>()
                                  {
                                      new EmailVariable("client_name", user_view.full_name),
                                      new EmailVariable("email_login", user_view.email),
                                      new EmailVariable("password", user_view.password),
                                  };

                bool send_email_client = false;
                send_email_client = SendWebEmail(mail_id, lst_content, user_view.email, "", "");
                Session["member_id"] = new_id;

                ViewBag.result_message = "Đăng ký thành công.";
                ViewBag.result = true;
                ViewBag.redirect = "/tai_khoan_ca_nhan.ub";
                return PartialView("../Shared/control_redirect");
            }
            else
            {
                ViewBag.result_message = "Đăng ký không thành công.";
                ViewBag.result = false;
                return PartialView("../Shared/member/register", user_view);
            }
        }

        #region forgot_password
        public ActionResult member_forgot_password()
        {
            return PartialView("../member/member_forgot_password");
        }

        [ChildActionOnly]
        [HttpGet]
        public ActionResult ctr_forgot_password()
        {
            var forgot = new ViewModels.ForgotPasswordViewModels();
            HttpCookie ck = HttpContext.Request.Cookies["Sercurity_User"];
            if (ck != null)
            {
                forgot.username = ck.Values["username"];
            }
            return PartialView("../Shared/member/control_forgot_password", forgot);
        }

        [ChildActionOnly]
        [HttpPost]
        public ActionResult ctr_forgot_password(FormCollection collection)
        {
            cryptography_component cryCom = new cryptography_component();
            web.component.email_component email_com = new email_component();
            var forgot = new ViewModels.ForgotPasswordViewModels();
            TryUpdateModel(forgot);
            try
            {
                var user = accountModels.authenticateAdmForgotPassword(forgot.email, forgot.email);

                int userForgot = user != null ? user.user_id : 0;
                if (userForgot > 0)
                {
                    var ustring = new Ustring();
                    string newPassword = ustring.RandomString(6, true);
                    string _password = cryCom.MD5(newPassword);
                    string _salt = _password.Substring(0, 5);
                    string _cryptography_password = System.Configuration.ConfigurationManager.AppSettings["CryptographyPassword"].ToString();
                    string _initial_vector = System.Configuration.ConfigurationManager.AppSettings["InitialVector"].ToString();
                    string pass = cryCom.Encrypt(_password, _cryptography_password, _salt, _initial_vector);

                    user.password = pass;

                    var mail_id = global_const.EMAIL_ID_FORGOT_PASSWORD;
                    var customer = checkoutModels.GetCustomerByUserID(userForgot);
                    var full_name = "";
                    if (customer != null)
                    {
                        full_name = customer.full_name;
                    }
                    var lst_content = new List<EmailVariable>()
                                  {
                                      new EmailVariable("client_name",full_name),
                                      new EmailVariable("password", newPassword)
                                  };
                     var check_send_email_password = SendWebEmail(mail_id, lst_content, forgot.email, "", "");

                    //cap nhat lai
                    if (check_send_email_password)
                    { 
                        user.salt = cryCom.MD5(newPassword).Substring(0, 5);
                        accountModels.changePassword(user);
                    }

                    if (check_send_email_password)
                    {
                        ViewBag.result_message = "Mật khẩu mới đã được gửi tới email của quý khách. Xin vui lòng đăng nhập tài khoản email để cập nhật mật khẩu.";
                        ViewBag.result = true;
                    }
                    else 
                    {
                        ViewBag.result_message = "Mật khẩu mới không thể gửi tới email của quý khách. Xin vui lòng liên hệ với quản trị để được hỗ trợ.";
                        ViewBag.result = false;
                    }
                }
            }
            catch
            {
                return PartialView("../Shared/member/control_forgot_password", forgot);
            }
            
            return PartialView("../Shared/member/control_forgot_password", forgot);
        }
        #endregion

        [ChildActionOnly]
        public ActionResult member_infor()
        {
            var user_view = new ViewModels.MemberViewModels();
            if (Session["member_id"] != null)
            {
                var user = accountModels.getUserByID(int.Parse(Session["member_id"].ToString()));
                if (user != null)
                {
                    var cus = checkoutModels.GetCustomerByUserID(user.user_id);
                    user_view.email = user.email;
                    if (cus != null)
                    {
                        user_view.full_name = cus.full_name;
                        user_view.address = cus.address;                   
                        user_view.mobile = cus.mobile;
                    }
                }
            }
            return PartialView("../Shared/member/member_infor", user_view);
        }

        [ChildActionOnly]
        [HttpGet]
        public ActionResult member_infor_update()
        {
            var user_view = new ViewModels.MemberViewModels();
            if (Session["member_id"] != null)
            {
                var user = accountModels.getUserByID(int.Parse(Session["member_id"].ToString()));
                if (user != null)
                {
                    var cus = checkoutModels.GetCustomerByUserID(user.user_id);
                    user_view.user_id = user.user_id;
                    user_view.email = user.email;
                    if (cus != null)
                    {
                        user_view.full_name = cus.full_name;
                        user_view.address = cus.address;
                        user_view.mobile = cus.mobile;
                    }
                }
                user_view.user_id = user.user_id;
            }
            return PartialView("../Shared/member/member_infor_update", user_view);
        }

        [ChildActionOnly]
        [HttpPost]
        public ActionResult member_infor_update(FormCollection values)
        {
            var user_view = new ViewModels.MemberViewModels();
            TryUpdateModel(user_view);

            //valid form in server code
            if (string.IsNullOrEmpty(user_view.full_name))
            {
                ViewBag.result_message = "Xin vui lòng điền Họ và Tên.";
                ViewBag.result = false;
                return PartialView("../Shared/member/member_infor_update", user_view);
            }
                      
            if (string.IsNullOrEmpty(user_view.email))
            {
                ViewBag.result_message = "Xin vui lòng nhập email.";
                ViewBag.result = false;
                return PartialView("../Shared/member/member_infor_update", user_view);
            }

            if (string.IsNullOrEmpty(user_view.mobile))
            {
                ViewBag.result_message = "Xin vui lòng nhập số điện thoại có giá trị.";
                ViewBag.result = false;
                return PartialView("../Shared/member/member_infor_update", user_view);
            }

            //check captcha text
            //if (HttpContext.Session["captchastring"] != null && user_view.captcha_text != HttpContext.Session["captchastring"].ToString())
            //{
            //    ViewBag.result_message = "Xin vui lòng nhập lại mã xác nhận.";
            //    ViewBag.result = false;
            //    return PartialView("../Shared/member/member_infor_update", user_view);
            //}

            web.data.entities.users user = accountModels.getUserByID(user_view.user_id ?? 0);
            if(user!=null && !string.IsNullOrEmpty(user_view.email) && user.email !=user_view.email)
            {
                if (!accountModels.CheckEmailExists(user_view.email))
                {
                    ViewBag.result_message = "Email này đã được sử dụng.";
                    ViewBag.result = false;
                    return PartialView("../Shared/member/member_infor_update", user_view);
                }

                user.username = user_view.username;
                user.email = user_view.email;

                accountModels.editUserMember(user);
            }
                                                        
            web.data.entities.customer cus = checkoutModels.GetCustomerByUserID(user_view.user_id??0);
            if (cus != null)
            {
                cus.full_name = user_view.full_name;
                cus.mobile = user_view.mobile;
                cus.email = user_view.email;
                cus.address = user_view.address;
                cus.user_id = user_view.user_id ?? 0;

                accountModels.editUserMemberInfor(cus);
            }
            

            ViewBag.result_message = "Cập nhật thông tin liên hệ thành công.";
            ViewBag.redirect = "/tai_khoan_ca_nhan.ub";
            return PartialView("../Shared/control_redirect");
        }

        public ActionResult member_order_history()
        {
            IsMember();
            return PartialView("../member/member_order_history");
        }

        public ActionResult member_infor_edit()
        {
            IsMember();
            return PartialView("../member/member_infor_edit");
        }


        [ChildActionOnly]
        public ActionResult control_order_list()
        {
            var order_view = new ViewModels.OrderHistoryViewModels();
            if (Session["member_id"] != null)
            {
                var user = accountModels.getUserByID(int.Parse(Session["member_id"].ToString()));
                if (user != null)
                {
                    order_view.list_order = accountModels.GetListOrderByMember(user.user_id);
                }
            }
            return PartialView("../Shared/member/control_order_list", order_view);
        }

        public ActionResult GetOrderDetailHistory(string id)
        {
            int? languageId = languageModels.GetLanguageIDbyUrl(Request.Url.PathAndQuery);
            var list_detail = accountModels.GetOrderDetailByOrderHistory(int.Parse(id), (int)languageId);
            var results = web.bussines.my_extensions.ToJSON(list_detail);
            return Json(results);
        }
    }
}
